<?php

include "databaseConnection.php";

function db_connect() {
  mysql_connect(localhost,$dbname, $dbpassword);
  @mysql_select_db($dbname) or die("Unable to select database");
}

function db_close() {
  mysql_close();
}

function login($username, $password) {
  db_connect();
  //Fetch userdata for input username
  $query = "SELECT * FROM user WHERE name='$username'";
  $result = mysql_query($query);
  if(mysql_numrows($result) == 0) return -1; //No such user

  $hash = mysql_result($result,0,"hash");

  if($hash != md5($password)) return -2; //Invalid password

  $expire=time()+60*60*24*30; //30 Days
  setcookie("campaign_user", $username, $expire);
  setcookie("campaign_hash", $hash, $expire);

  db_close();
  return 0;
}

function register($username, $password) {
  db_connect();

  //Check uniqueness of username
  $query = "SELECT * FROM user WHERE name='$username'";
  $result = mysql_query($query);
  if(mysql_numrows($result) != 0) return -1; //Username already taken

  $md5 = md5($password);  
  $query = "INSERT INTO user (name,hash) VALUES('$username','$md5')";

  mysql_query($query);

  db_close();
  return 0;
}

function logout() {
  setcookie("campaign_user", "", time()-3600);
  setcookie("campaign_hash", "", time()-3600);
}

function authenticate() {
  $username = $_COOKIE["campaign_user"];
  $hash = $_COOKIE["campaign_hash"];

  db_connect();
  $query = "SELECT * FROM user WHERE name='$username'";
  $result = mysql_query($query);
  if(mysql_numrows($result) == 0) return -1;

  $md5 = mysql_result($result,0,"hash");

  if($md5 != $hash) return -1;

  db_close();
  return mysql_result($result,0,"privilege");
}

?>
